package cn.gok.web;

import cn.gok.entity.TDormitory;
import cn.gok.entity.TDormitoryPositon;
import cn.gok.entity.TManager;
import cn.gok.entity.TStudent;
import cn.gok.service.ManagerService;
import cn.gok.service.impl.ManagerServiceImpl;
import cn.gok.util.MapObjectUtil;
import cn.gok.util.R;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.SneakyThrows;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/managerTest")
public class ManagerServlet extends HttpServlet {
    ManagerService managerService = new ManagerServiceImpl();
    //定义一个集合存储图片的后缀的格式
    private static List<String> Excel = new ArrayList<>();
    static {
        Excel.add(".xls");
    }

    @SneakyThrows
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        switch (action) {
            case "addStudent": addStudent(req, resp);break;
            case "queryStudent":queryStudent(req,resp);break;
            case "addDormitory":addDormitory(req,resp);break;
            case "queryPosition":queryPosition(req,resp);break;
            case "queryApartmentName":queryApartmentName(req,resp);break;
            //批量录入学生信息
            case "batchAddStudentInfo": batchAddStudentInfo(req, resp);break;
            //修改宿舍信息
            case "updateDormitory":updateDormitory(req,resp);break;
            //查询楼层
            case "queryFloor":queryFloor(req,resp);break;
            //宿舍信息查询
            case "queryDormitory":queryDormitory(req,resp);break;
            //学生入住
            case "studentCheckIn": studentCheckIn(req, resp);break;
            //获取所有宿舍的信息
            case "queryAllDoorNumByDormPosId":queryAllDoorNumByDormPosId(req, resp);break;
            //通过选择的寝室去查询该寝室是否还有剩余床位
            case "querySurplusNumByDoor": querySurplusNumByDoor(req, resp);break;
            //判断学号是否存在
            case "checkStuId":checkStuId(req,resp);break;
            //查询位置
            case "queryAllDormitoryPosition":queryAllDormitoryPosition(req, resp);break;
            //退寝
            case "out":out(req,resp);break;
            //判断学生是否入住
            case "queryStudentLive":queryStudentLive(req,resp);break;
            //表格
            case "queryAll":queryAll(req,resp);break;

        }
    }

    public void addStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String realName = req.getParameter("realName");
        String stuName = req.getParameter("stuName");
        String password = req.getParameter("password");
        String gender = req.getParameter("gender");
        int age = Integer.parseInt(req.getParameter("age"));
        String schoolName = req.getParameter("schoolName");
        String phoneNum = req.getParameter("phoneNum");

        R r = managerService.addStudent(realName, stuName, password, gender, age, schoolName, phoneNum);

        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }

    public void queryStudent(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException {
        String realName = req.getParameter("realName");
        String gender = req.getParameter("gender");
        String schoolName = req.getParameter("schoolName");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        int currPage = Integer.parseInt(req.getParameter("currPage"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        //日期格式
        if (startTime.equals("")){
            startTime=null;
        }
        if (endTime.equals("")){
            endTime=null;
        }


//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date startTime1 = sdf.parse(startTime);
//            Date endTime1 = sdf.parse(endTime);


        R r = managerService.queryStudent(realName, gender, schoolName, startTime,endTime, currPage, pageSize);
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }
    public void addDormitory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String position = req.getParameter("position");
        String apartmentName = req.getParameter("apartmentName");
        String floor = req.getParameter("floor");
        String doorNum = req.getParameter("doorNum");
        String max = req.getParameter("max");
        String type = req.getParameter("type");
        String sate = req.getParameter("sate");

        TManager manager = (TManager) req.getSession().getAttribute("manager");
        R r = managerService.addDormitory(position, apartmentName, floor, doorNum, max, type, sate, manager.getManagerId());
        resp.getWriter().println(JSONUtil.toJsonStr(r));

    }

    public void queryPosition(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("Content-type", "application/json;charset=utf-8");
        resp.setContentType("application/json;charset=utf-8");
        R r = managerService.queryPosition();
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }
    public void queryApartmentName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("Content-type", "application/json;charset=utf-8");
        resp.setContentType("application/json;charset=utf-8");
        R r = managerService.queryApartmentName();
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }

    public void batchAddStudentInfo(HttpServletRequest req, HttpServletResponse resp){
        resp.setHeader("Content-type", "application/json;charset=utf-8");
        resp.setContentType("application/json;charset=utf-8");
        //获取commons.fileupload 提供的工厂对象
        FileItemFactory factory = new DiskFileItemFactory();
        // 根据工厂对象获取文件上传对象（fileupload）
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        Map<String, List<FileItem>> parameterMap = null;
        try {
            parameterMap = fileUpload.parseParameterMap(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        List<FileItem> fileItems1 = parameterMap.get("myfile");
        FileItem fileItem = fileItems1.get(0);
        System.out.println("----"+fileItem);

        String name = fileItem.getName();
        System.out.println("++++"+name);
        // 得到后缀名
        String excel = name.substring(name.lastIndexOf("."));

        //判断文件格式是否正确
        if(!Excel.contains(excel)){
            try {
                resp.getWriter().println(JSONUtil.toJsonStr(R.fail("文件格式")));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        //获取当前项目的根路径
        String contextPath = req.getSession().getServletContext().getRealPath("");

        //创建出文件的存储路径
        File file = new File(contextPath + File.separator +"Excel");
        System.out.println("////"+file);
        //如果文件夹不存在，则创建
        if(!file.exists()){
            file.mkdirs();
        }
        //写出文件到指定路径
        try {
            fileItem.write(new File(contextPath +
                    File.separator +"Excel"+File.separator+name));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String s = file + File.separator + name;
        System.out.println("qeqeqew"+s);
        //从文件中读取Excel为ExcelReader

        ExcelReader reader = ExcelUtil.getReader(s);
        List<Map<String,Object>> readAll = reader.readAll();
        try {

            List<TStudent>  students = MapObjectUtil.getObject(readAll, TStudent.class);
            int i = managerService.addStudents(students);
            System.out.println(i);


        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    //修改宿舍信息
    public void updateDormitory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String doorNum = req.getParameter("doorNum");
        String max = req.getParameter("max");
        String type = req.getParameter("type");
        String apartmentName = req.getParameter("apartmentName");
        String position = req.getParameter("position");
        String oldDoorNum = req.getParameter("oldDoorNum");
        R r = managerService.updateDormitory(doorNum, type, max, apartmentName, position, oldDoorNum);

        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }
    //查询楼层
    public void queryFloor(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String position = req.getParameter("position");
        String apartmentName = req.getParameter("apartmentName");
        R r = managerService.queryFloor(position, apartmentName);
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }
    //宿舍信息查询
    public void queryDormitory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String apartmentName = req.getParameter("apartmentName");
        String floor = req.getParameter("floor");
        String type = req.getParameter("type");
        String state = req.getParameter("state");
        int currPage = Integer.parseInt(req.getParameter("currPage"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        R r = managerService.queryDormitory(apartmentName, floor, type, state, currPage, pageSize);
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }

    public void studentCheckIn(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int stuId = Integer.parseInt(req.getParameter("stuId"));
        int door_num = Integer.parseInt(req.getParameter("doorNum"));
        TDormitory dormitory = managerService.queryDormitoryByDoor(door_num);
        Integer dormId = dormitory.getDorId();
        R r = managerService.studentCheckIn(stuId, dormId);
        //将剩余人数减1，并将宿舍状态更改为与入住学生性别相对应的状态
        TStudent student = (TStudent) req.getSession().getAttribute("student");
        if (student.getGender().equals("男")){
            managerService.reduceSurplusNumByDoor(door_num,1);
        }else if (student.getGender().equals("女")){
           managerService.reduceSurplusNumByDoor(door_num,2);
        }
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }

    /*
     * 通过楼房id和学生性别获取该楼房所有可入住的宿舍编号
     * */
    public void queryAllDoorNumByDormPosId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        TStudent student = (TStudent) req.getSession().getAttribute("student");
        System.out.println("888888888888"+student);
        if (student.getGender().equals("男")){
            List<TDormitory>  dormitories = managerService.queryAllDoorNumByDormPosId(id,2);
            resp.getWriter().println(JSONUtil.toJsonStr(dormitories));
        }else if (student.getGender().equals("女")){
            List<TDormitory>  dormitories = managerService.queryAllDoorNumByDormPosId(id,1);
            resp.getWriter().println(JSONUtil.toJsonStr(dormitories));
        }
    }

    /*
     * 通过选择的寝室去查询该寝室是否还有剩余床位
     * */
    public void querySurplusNumByDoor(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int door_num = Integer.parseInt(req.getParameter("doorNum"));
        R r = managerService.querySurplusNumByDoor(door_num);
        System.out.println(r);
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }

    //判断学号是否存在
    public void checkStuId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String stuId = req.getParameter("stuId");
        TStudent student = managerService.queryStudentById(stuId);
        req.getSession().setAttribute("student",student);
        resp.getWriter().println(JSONUtil.toJsonStr(student));
    }
    //查询所有位置信息
    public void queryAllDormitoryPosition(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<TDormitoryPositon> dormitoryPositions = managerService.queryAllDormitoryPosition();
        resp.getWriter().println(JSONUtil.toJsonStr(dormitoryPositions));
    }
    //退寝
    public void out(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String stuId = req.getParameter("stuId");
        R out = managerService.out(stuId);
        managerService.addSurplus(stuId);
        resp.getWriter().println(JSONUtil.toJsonStr(out));
    }
  //判断学生是否入住
    public void queryStudentLive(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String stuId = req.getParameter("stuId");
        R r = managerService.queryStudentLive(stuId);
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }

    public void queryAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        R r = managerService.queryAll();
        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }
}